﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsMine.DomainObjects;
using NewsMine.Utilities;
using NewsMine.Storage;
using NewsDiscoveryEngine.Jobs;

namespace NewsDiscoveryEngine
{
    [Serializable]
    public class HtmlFeedDetailsFromTargetUrlJob : BaseJob
    {
        public NewsMine.DomainObjects.FeedItem FeedItem { get; set; }

        public override bool ExecuteJob()
        {
            NewsMine.DomainObjects.FeedItem resutedfeedItem = FeedItem;

            try
            {
                resutedfeedItem = this.GetDetailedFeedItemFromTargetUrl(this.FeedItem);
            }
            catch (Exception ex)
            {
                //if some thing goes wrong here (while getting details from the target url)... let the old feed go and process that.
                TempLogger.Log("Error while processing Details from target Url:" + ex.Message, ex);
            }

            if (resutedfeedItem != null)
            {
                if (resutedfeedItem.PubDate == DateTime.MinValue)
                {
                    resutedfeedItem.PubDate = DateTime.UtcNow;
                }

                resutedfeedItem.UpdatedDateTime = resutedfeedItem.PubDate;
            }
            base.ProcessOutput(resutedfeedItem);
            return true;
        }

        private NewsMine.DomainObjects.FeedItem GetDetailedFeedItemFromTargetUrl(NewsMine.DomainObjects.FeedItem feedItem)
        {

            HtmlContentFromUrl htmlContent = HtmlDownloadJob.DownloadHtmlContent(feedItem.Link);
            //todo: whenver we need to save html content we need to enable this.
            //Defaults.HtmlDocumentStore.Replace(htmlContent.Url, htmlContent.HtmlContent);
            //Defaults.HtmlDocumentStore.Close();

            NewsMine.DomainObjects.FeedItem feedItemFromMetaData = WebHelper.GetFeedItemFromTargetUrl(htmlContent);

            string description = string.Empty;

            if (feedItem.IsFeedSourced)
            {
                description = feedItem.Description;
            }

            var resultFeed = UtilityExtn.GetMergedFeedItem(feedItem, feedItemFromMetaData);

            //todo: here calculate the image size and post it to the index processor.

            CalculateFeedImageSizeJob.CalculateImageSizeForFeedImage(resultFeed);

            return resultFeed;

        }




    }
}
